package com.moment.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.moment.model.GlobalClass;
import com.moment.model.UserReg;
import com.moment.model.WalletData;
import com.moment.util.Converter;
import com.moment.webservice.Services;
import com.moment.webservice.ServicesProxy;

@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginController() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doLogin(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doLogin(request, response);
	}

	protected void doLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();

		String userid = request.getParameter("loginid").trim();
		String password = request.getParameter("password").trim();
		password = GlobalClass.encryptpass(password);
		System.out.println("login id=" + userid + " password" + password);
	
		if (userid == null || password == null || userid.equals("")
				|| password.equals("")) {
			session.setAttribute("error", "Enter your Username and Password");
			response.sendRedirect("/MMP/jsp/index.jsp");
		} else {
			//--New CODE-------------
			Map<String,String> map=new HashMap<String,String>();
			map.put("method", "4");
			map.put("username", userid);
			map.put("password", password);
			String json=new Converter().mapToJson(map);
			System.out.println("json String :"+json);
			Services serviceproxy=new ServicesProxy();
			
			String ss=serviceproxy.service(json);
			//---------------------------
			//--old code-----------------
//			WebsProxy proxy = new WebsProxy();
//			String ss = proxy.login(userid, password);
			//----------------------------
			System.out.println("Data From webservices" + ss);
			JSONArray jArray, logindet, nicknames;
			JSONObject jobj = null, statusobj = null;
			String type = null, forward = null, status = null;
			if (ss == null) {
				System.out.println("out put String NUll");
			}
			try {
				jArray = new JSONArray(ss);
				jobj = jArray.getJSONObject(0);
				status = jobj.getString("status");
				System.out.println("status reply:" + status);
				if (status.equals("00")) {
					System.out.println("inside status" + status);
					System.out.println("jarray=" + jArray.getJSONArray(1));
					logindet = jArray.getJSONArray(1);
					System.out.println("logindet=" + logindet);
					UserReg userObj = new UserReg();
					WalletData walletObj = new WalletData();
					walletObj.nicknames = new JSONArray();
					walletObj.setNicknames(jArray.getJSONArray(2));
					walletObj.setInstru(jArray.getJSONArray(2).toString());
					jobj = logindet.getJSONObject(0);
					type = jobj.getString("type");
					String name = jobj.getString("Name");
					userObj.setImagestr(jobj.getString("img"));
					System.out.println("img=" + jobj.getString("img"));
					userObj.setQrcode(jobj.getString("qrcode"));
					userObj.setMob(jobj.getString("mobilenumber"));

					userObj.setUserID(name);
					userObj.setTypeofmember(type);
					userObj.setName1(name);
					/*
					 * session creation and max time set for cookies
					 */

					session.setMaxInactiveInterval(30 * 60);
					Cookie userName = new Cookie("user", userObj.getMob());
					userName.setMaxAge(30 * 60);
					response.addCookie(userName);
					// //////////////////////////////////////////////////////////////
					session.setAttribute("username", userObj.getMob());
					session.setAttribute("userObj", userObj);
					session.setAttribute("walletObj", walletObj);

					if ("customer".equalsIgnoreCase(type)) {
						// redirection
						System.out.println("customer");
						forward = "jsp/viewprofile.jsp";
						// request.getRequestDispatcher("jsp/viewprofile.jsp").forward(request,
						// response);
						// response.sendRedirect("/MMP/jsp/viewprofile.jsp");
					} else if ("merchant".equalsIgnoreCase(type)) {
						// redirection
						forward = "jsp/viewprofile.jsp";

					} else if ("cashier".equalsIgnoreCase(type)) {
						// redirection
						forward = "jsp/cashier.jsp";

					} else {
						// redirection
					}
					response.sendRedirect("/MMP/" + forward);
					// RequestDispatcher view = request
					// .getRequestDispatcher(forward);
					// view.forward(request, response);
				} else if (status.equals("01")) {
					System.out.println("Already Logged In Another Device");
					session.setAttribute("error",
							"Already Logged In Another Device");
					// getServletContext().getRequestDispatcher("/jsp/index.jsp").forward(request,
					// response);
					response.sendRedirect("/MMP/jsp/index.jsp");
				} else if (status.equals("02")) {
					System.out.println("Username/Password Incorrect");
					session.setAttribute("error", "Username/Password Incorrect");
					// getServletContext().getRequestDispatcher("/jsp/index.jsp").forward(request,
					// response);
					response.sendRedirect("/MMP/jsp/index.jsp");
				} else if (status.equals("03")) {
					System.out.println("Database Problem");
					session.setAttribute("error", "Connection Lost");
					// getServletContext().getRequestDispatcher("/jsp/index.jsp").forward(request,
					// response);
					response.sendRedirect("/MMP/jsp/index.jsp");
				} else {

					session.setAttribute("error", "Connection Lost");
					// getServletContext().getRequestDispatcher("/jsp/index.jsp").forward(request,
					// response);
					response.sendRedirect("/MMP/jsp/index.jsp");
				}

			}

			catch (Exception e) {
				session.setAttribute("error", "Error");
				response.sendRedirect("/MMP/jsp/index.jsp");
				// request.getRequestDispatcher("jsp/index.jsp").forward(
				// request, response);

			}

		}

	}

}
